<?php
namespace Application\Controller;

use Com\Mvc\Controller\BaseController;
use Zend\View\Model\ViewModel;
use Zend\Session\Container;
use Zend\Authentication\Adapter\DbTable;
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Result;

class UserIdentittyController extends BaseController{
	public function __construct(){
		parent::__construct();
		$this->userModel = $this->serviceManager->get('Test\user');
	}
	public function indexAction(){
		$view = new ViewModel();
		$session = new Container();
		$session->offsetSet("SESS","YUHYAA");
		return $view;
	}
	public function loginAction(){
		$session = new Container();
		$value = $session->offsetGet("SESS");
		echo $value;
		exit;
	}
	
	/**
	 * 用户认证
	 */
	public function authAction(){
		$request = $this->getRequest();
		if($request->isXmlHttpRequest()){
			$post = $request->getPost()->toArray();
			$session = new Container();
			$userData = array(
				"username"=>$post['username'],
				"password"=>$post['password']
			);
			$adapter = $this->serviceManager->get('Zend\Db\Adapter\Adapter');
			$authAdapter = new DbTable($adapter,'user','name','password','?');
			$authAdapter->setIdentity($userData['username'])->setCredential($userData['password']);
			
			$auth = new AuthenticationService();
   			$result = $auth->authenticate($authAdapter);
   			
			if(!$result->isValid()){
	   			//认证不通过，返回错误信息
	   			switch($result->getCode()){
	   				case Result::FAILURE_IDENTITY_NOT_FOUND:
	   					$this->ajaxReturn(300,'用户名不存在!');
	   					break;
	   				case Result::FAILURE_CREDENTIAL_INVALID:
	   					$this->ajaxReturn(300,'密码错误!');
	   					break;
	   				default:
	   					$this->ajaxReturn(300,'登录失败!');
	   					break;
	   			}
	   		}
	   		
	   		//认证结果
   			$user = $authAdapter->getResultRowObject();
   			//写入Session
	   		$auth->getStorage()->write((object)array(
	   				'id' => $user->id,
	   				'username' =>$user->username,
	   				'realname' => $user->realname,
	   		));
			
		}else{
			$this->ajaxReturn(300, "请求非法！");
		}
	}
	/**
	 * 生成登录所需要的验证码图片
	 * @return image
	 */
	 
	public function captchaAction()
	{
		$session = new Container();
		$word = '';

		for($i=0;$i<4;$i++){
			$word .= dechex(mt_rand(0,15));
		}

		$sessionValueOfCaptcha = md5(strtolower($word));
		$session->offsetSet('captcha',$sessionValueOfCaptcha);

		$img = imagecreate(102,28);
		imagefill($img,0,0,imagecolorallocate($img,10,52,92));
		imagestring($img,5,mt_rand(18,20),mt_rand(5,8),$word,imagecolorallocate($img, 255,255,255));

		header('Content-Type:image/png');
		imagepng($img);
		imagedestroy($img);

		return false;
	  
	}//function captchaAction() end
	 
	 
	public function demoAction(){
		$id = $this->params('id', false);		
		echo $this->getRequest()->getRequestUri();
		exit;
	}
}

?>